//
//  DBManager.swift
//  MyProject
//
//  Created by volantPig on 2020/11/11.
//

import UIKit
import CoreData

class DBManager: NSObject {
    static let `default` = DBManager()
    
    func getContext() -> NSManagedObjectContext {
        return DBHelper.default.context
    }
    
    /// 执行存储操作
    func saveContext() {
        do {
            try DBManager.default.getContext().save()
        } catch  {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
    
    func saveData(data: String) {
        let newValue = NSEntityDescription.insertNewObject(forEntityName: "HistoryData", into: DBManager.default.getContext()) as! HistoryData
        newValue.dateKey = Tools.getCurrentTimeyyyyMMddHHmmss()
        newValue.dateValue = data
        DBManager.default.saveContext()
    }
    
    func getAllLocalData() -> [HistoryData] {
        let fetchRequest: NSFetchRequest = HistoryData.fetchRequest()
        do {
            let result = try DBManager.default.getContext().fetch(fetchRequest)
            return result
        } catch  {
            fatalError()
        }
    }
    
    func deleteAllLocalData() {
        let result = DBManager.default.getAllLocalData()
        for info in result {
            DBManager.default.getContext().delete(info)
        }
        DBManager.default.saveContext()
    }
    
}
